<!DOCTYPE html>
<html>
<head>
<title>Bit.ly Shortener</title>
</head>
<body>
	
<script type="text/javascript">	
var loginvar = safari.extension.settings.login;
var api_keyvar = safari.extension.settings.api_key;

function bitChange() {
if (event.key == "login")
   {
   loginvar=event.newValue;
   }
if (event.key == "api_key")
   {
   api_keyvar=event.newValue;
   }
}
 
safari.application.addEventListener("change",bitChange,false);

function performCommand(event)
{
    if (event.command === "shortener") {
    	loginvar = safari.extension.settings.login;
    	api_keyvar = safari.extension.settings.api_key;
        var currentURL = event.target.browserWindow.activeTab.url;
        currentURL = escape(currentURL);
        if (currentURL && loginvar && api_keyvar){
        	event.target.browserWindow.openTab().url = 'http://api.bit.ly/v3/shorten?login='+loginvar+'&apiKey='+api_keyvar+'&longUrl='+ currentURL+'&format=txt';             
        }
        else
        	alert('Check your Bit.ly preferences. Login: '+loginvar+' API Key: '+api_keyvar);
    }
}
 
function validateCommand(event)
{
    if (event.command === "shortener") {
        // Disable the button if there is no URL loaded in the tab.
        event.target.disabled = !event.target.browserWindow.activeTab.url;
    }
}
 
// if event handlers are in the global HTML page,
// register with application:
safari.application.addEventListener("command", performCommand, false);
safari.application.addEventListener("validate", validateCommand, false);
// if event handlers are in an extension bar,
// register with parent window:
// safari.self.browserWindow.addEventListener("command", performCommand, false);
// safari.self.browserWindow.addEventListener("validate", validateCommand, false);
</script>
</body>
</html>